<template>
  <ModelDetailDrawerLayout
    v-model:visible="drawerVisible"
    :title="props.title"
    :modelDetail="props.modelDetail"
    :stage="props.stage"
  >
    <ModelDetailDrawerBody
      ref="detailBodyRef"
      :title="props.subTitle"
      :collapseConfig="collapseConfig"
      :modelNo="modelNo"
      :life-cycle-stage="props.stage"
      @refresh="handleRefresh"
    >
      <template #content="{ item, index }">
        <div class="g-pb12">
          <el-button
            type="primary"
            @click="handleAdd(item.processNo)"
            v-btnPermission="'PCF_PROCESS_DATA_EDIT'"
            ><CIcon class="g-mr4" type="c-xian-xinjian"></CIcon>{{ addBtnText }}</el-button
          >
        </div>
        <CTable
          :ref="el => (tableRefs[index] = el)"
          :key="item.processNo"
          :data-source="item.processDataList"
          useDataSource
          :pagination="false"
          border
        >
          <template v-for="item in columns" :key="item.id">
            <vxe-column
              :title="item.title"
              :field="item.field"
              show-overflow="tooltip"
              v-bind="getBind(item)"
            >
              <template #header v-if="!isTransferStage && item.field === 'dosage'">
                <div class="g-flex-start-center"
                  >{{ item.title }}
                  <el-tooltip content="用量最多保留9位小数" placement="top">
                    <CIcon class="g-ml4 g-cur-poi dosage-tips-icon" type="c-xian-shuoming"></CIcon>
                  </el-tooltip>
                </div>
              </template>
              <template #default="scope">
                <CTableEditCell
                  :modelValue="scope.row.unit == 'pcs' ? scope.row.quantity : scope.row[item.field]"
                  inputType="number"
                  :tableRow="scope.row"
                  trigger="click-cell"
                  placeholder="请输入"
                  :digit="9"
                  showPlaceholderStyle
                  :updateFn="handleDosageUpdate"
                  :local-value-formatter="handleLocalValueFormatter"
                  v-if="
                    !isTransferStage &&
                    item.field === 'dosage' &&
                    hasBtnPermission('PCF_PROCESS_DATA_EDIT')
                  "
                ></CTableEditCell>
                <template v-else>
                  {{
                    item.render ? item.render({ record: scope.row }) : empty(scope.row[item.field])
                  }}
                </template>
              </template>
            </vxe-column>
          </template>
          <vxe-column title="操作" fixed="right" :minWidth="180">
            <template #default="scope">
              <CTableButtonGroup
                :showMoreNum="3"
                :buttons-config="
                  getTableButtonsConfig(scope.row, item.processDataList, item, index)
                "
              ></CTableButtonGroup>
            </template>
          </vxe-column>
        </CTable>
      </template>
    </ModelDetailDrawerBody>
    <FlowDialog
      v-model:visible="dialogVisible"
      :stage="props.stage"
      :flowItem="tempProcessItem"
      :processNo="tempProcessNo"
      :modelNo="modelNo"
      :nodeNo="tempNodeNo"
      @refresh="handleRefresh"
    ></FlowDialog>
    <RelateInventoryDialog
      v-model:visible="dialogVisibleRelate"
      :processNo="tempProcessNo"
      :modelNo="modelNo"
      :nodeNo="tempNodeNo"
      @refresh="handleRefresh"
      @select="handleSelect"
    ></RelateInventoryDialog>
    <TransportDialog
      v-model:visible="transportDialogVisible"
      :flowItem="tempProcessItem"
      :processNo="tempProcessNo"
      :modelNo="modelNo"
      :modelDetail="props.modelDetail"
      :nodeNo="tempNodeNo"
      @refresh="handleRefresh"
    ></TransportDialog>
    <SiteDataDialog
      :title="siteDataDialogTitle"
      v-model:visible="siteDataDialogVisible"
      readonly
      type="MODEL"
      :modelNo="modelNo"
      :stage="ProcessStageCodeEnum.USE_STAGE"
      :nodeNo="nodeNo"
      :nodeCode="nodeCode"
    ></SiteDataDialog>
  </ModelDetailDrawerLayout>
</template>

<script lang="ts" setup name="ProductBomDrawer">
import { defineProps, defineEmits, computed, ref, Ref, reactive } from 'vue';
import { CTable, CTableButtonGroup } from '@/components/CTable';
import type { TableButtonItem } from '@/components/CTable';
import { FlowDialog } from './components/FlowDialog';
import { TransportDialog } from './components/TransportDialog';
import RelateInventoryDialog from './components/RelateInventoryDialog/index.vue';
import ModelDetailDrawerLayout from '../ModelDetailDrawerLayout/index.vue';
import ModelDetailDrawerBody from '../ModelDetailDrawerBody/index.vue';
import { useMessage } from '@/hooks/useMessage';
import { empty, rateToNumber, limitStrLength } from '@/utils';
import type { ProcessDataItem, ProcessListItem } from '@/apis/pcf/myModel/model/modelDetailModel';
import type { ModelDetailResult } from '@/apis/pcf/myModel/model/modelManage';
import { editStageFlow, deleteStageFlow } from '@/apis/pcf/myModel/modelDetail';
import { FuelTypeMAP, ProcessStageCodeEnum, TransportMethodMap } from '@/constants/enum';
import { getSystemDict } from '@/apis/common/common';
import { uniqWith, isEqual } from 'lodash';
import { CTableEditCell } from '@/components/CTableEditCell';
import { findItemInTree } from '@/utils';
import SiteDataDialog from '../ProductBomDrawer/components/SiteDataDialog/index.vue';

import { hasBtnPermission } from '@/directives/btnPermission';

interface ProductBomDrawerProps {
  title: string;
  subTitle: string;
  stage: keyof typeof ProcessStageCodeEnum;
  visible: boolean;
  modelNo: string;
  modelDetail?: ModelDetailResult;
}
const props = defineProps<ProductBomDrawerProps>();
const emits = defineEmits(['update:visible', 'refresh']);
const { createConfirm, createMessage } = useMessage();
const tableRefs = reactive({} as { [key: number]: any });
const drawerVisible = computed({
  get: () => {
    return props.visible;
  },
  set: (value: boolean) => {
    emits('update:visible', value);
  }
});

/**
 * 是否是运输阶段
 */
const isTransferStage = computed(() => {
  return props.stage === ProcessStageCodeEnum.TRANSFER_STAGE;
});
/**
 * 新增按钮 文案
 */
const addBtnText = computed(() => {
  if (isTransferStage.value) return '新增运输线路';
  return '新增输入/输出流';
});
/**
 * 配置表格的按钮
 * @param row 表格行数据
 */
function getTableButtonsConfig(
  row: ProcessDataItem,
  list: ProcessDataItem[],
  item: ProcessListItem,
  index: number
): TableButtonItem[] {
  let btnArr = [
    {
      text: '编辑',
      btnPermission: 'PCF_PROCESS_DATA_EDIT',
      onClick: () => handleEdit(row, item)
    }
  ];
  if (row.dataType == 'PART_REPLACE' && props.stage == ProcessStageCodeEnum.USE_STAGE) {
    btnArr.push({
      text: '部件信息',
      btnPermission: 'PCF_PROCESS_DATA_EDIT',
      onClick: () => handleSeeProduction(row, item)
    });
  }
  if (props.stage == ProcessStageCodeEnum.MANUFACTURE_STAGE) {
    btnArr = btnArr.concat([
      {
        text: '关联盘查数据',
        btnPermission: 'PCF_PROCESS_DATA_EDIT',
        onClick: () => handleRalate(row, item, index)
      },
      {
        text: '删除',
        btnPermission: 'PCF_PROCESS_DATA_DELETE',
        onClick: () => handleDelete(row.nodeNo, item)
      }
    ]);
  } else {
    btnArr = btnArr.concat([
      {
        text: '删除',
        btnPermission: 'PCF_PROCESS_DATA_DELETE',
        onClick: () => handleDelete(row.nodeNo, item)
      }
    ]);
  }
  return btnArr;
}

/**
 * 页面loading
 */
const loading = ref(false);

/**
 * 流弹窗 显示状态
 */
const dialogVisible = ref(false);

/**
 * 运输路径弹窗 显示状态
 */
const transportDialogVisible = ref(false);
const dialogVisibleRelate = ref(false);

/**
 * 工序item的临时变量（用于编辑流/运输路径弹窗）
 */
const tempProcessItem = ref<ProcessDataItem>();

/**
 * 流/运输路径弹窗 processNo
 * 有值：新增
 * 无值：编辑
 */
const tempProcessNo = ref('');

/**
 * 流/运输路径弹窗 nodeNo
 * 有值：编辑
 * 无值：新增
 */
const tempNodeNo = ref('');

/**
 * 新增流/运输路径
 */
function handleAdd(processNo: string) {
  console.log('handleAdd', processNo);
  tempProcessItem.value = undefined;
  tempProcessNo.value = processNo;
  tempNodeNo.value = '';
  if (isTransferStage.value) {
    transportDialogVisible.value = true;
  } else {
    dialogVisible.value = true;
  }
}

/**
 * 编辑流/运输路径
 */
function handleEdit(row: ProcessDataItem, item: ProcessListItem) {
  tempProcessItem.value = row;
  tempProcessNo.value = item.processNo;
  tempNodeNo.value = row.nodeNo;
  if (isTransferStage.value) {
    transportDialogVisible.value = true;
  } else {
    dialogVisible.value = true;
  }
}

/**
 * 查看场地数据
 */

const siteDataDialogTitle = ref('');
const nodeNo = ref('');
const nodeCode = ref('');
const siteDataDialogVisible = ref(false);
function handleSeeProduction(row: ProcessDataItem, item: ProcessListItem) {
  siteDataDialogTitle.value = row.nodeName;
  nodeNo.value = row.nodeNo;
  siteDataDialogVisible.value = true;
}

/**
 * 关联盘查数据
 */
const selectIndex = ref(0);
function handleRalate(row: ProcessDataItem, item: ProcessListItem, index: number) {
  selectIndex.value = index;
  tempProcessItem.value = row;
  tempProcessNo.value = item.processNo;
  tempNodeNo.value = row.nodeNo;
  dialogVisibleRelate.value = true;
}
/**
 * 删除流/运输路径
 */
function handleDelete(nodeNo: string, item: ProcessListItem) {
  // 产品使用阶段
  let msg = '确认删除输入输出流？';
  if (props.stage === 'MANUFACTURE_STAGE') {
    // 产品生产阶段
    msg = '确认删除输入输出流？';
  } else if (props.stage === 'TRANSFER_STAGE') {
    // 产品运输阶段
    msg = '确认删除运输线路？';
  }
  createConfirm('提示', msg, {
    iconType: 'warning',
    confirmButtonText: '删除'
  }).then(async () => {
    try {
      loading.value = true;
      await deleteStageFlow(nodeNo);
      handleRefresh(item.processNo);
      createMessage.success('删除成功！');
      loading.value = false;
    } catch (error) {
      console.log('error', error);
      loading.value = false;
    }
  });
}

const flowDataTypeMap = ref<Record<string, string>>({});
/**
 * 获取类型和名称 字典
 */
async function getTypeDict() {
  try {
    const res = await getSystemDict('FLOW');

    const uniqOpt = uniqWith(
      res.map(item => {
        return {
          label: item.dataDesc,
          value: item.dataGroup
        };
      }),
      isEqual
    );
    uniqOpt.push({
      label: '部件更换',
      value: 'PART_REPLACE'
    });
    uniqOpt?.forEach(item => {
      flowDataTypeMap.value[item.value] = item.label;
    });
  } catch (error) {
    console.log('error', error);
  }
}

getTypeDict();

/**
 * 折叠面板配置
 */
const collapseConfig = computed(() => {
  if (props.stage === ProcessStageCodeEnum.MANUFACTURE_STAGE) {
    return {
      addBtnText: '新增工序',
      editBtnText: '编辑工序名称',
      deleteBtnText: '删除工序'
    };
  } else {
    return {
      addBtnText: '新增情景',
      editBtnText: '编辑情景名称',
      deleteBtnText: '删除情景'
    };
  }
});

const columns = computed(() => {
  if (props.stage !== ProcessStageCodeEnum.TRANSFER_STAGE) {
    return [
      {
        id: 'dataType',
        title: '类型',
        field: 'dataType',
        minWidth: '150',
        render: ({ record }: { record: ProcessDataItem }) => {
          return flowDataTypeMap.value && record.dataType
            ? flowDataTypeMap.value[record.dataType]
            : '-';
        }
      },
      {
        id: 'nodeName',
        title: '名称',
        field: 'nodeName',
        minWidth: '150'
      },
      {
        id: 'dosage',
        title: '用量',
        field: 'dosage',
        minWidth: '120'
      },
      {
        id: 'unit',
        title: '单位',
        field: 'unit',
        minWidth: '100'
      },
      {
        id: 'remark',
        title: '备注',
        field: 'remark',
        minWidth: '150'
      }
    ];
  } else {
    return [
      {
        id: 'transferNodeName',
        title: '运输物',
        field: 'transferNodeName',
        minWidth: '150'
      },
      {
        id: 'transferMethod',
        title: '运输方式',
        field: 'transferMethod',
        minWidth: '150',
        render: ({ record }: { record: ProcessDataItem }) => {
          return empty(TransportMethodMap[record.transferMethod]);
        }
      },
      {
        id: 'fuelType',
        title: '燃料类型',
        field: 'fuelType',
        minWidth: '150',
        render: ({ record }: { record: ProcessDataItem }) => {
          return empty(FuelTypeMAP[record.fuelType]);
        }
      },
      {
        id: 'transferRate',
        title: '运载率',
        field: 'transferRate',
        minWidth: '150',
        render: ({ record }: { record: ProcessDataItem }) => {
          return rateToNumber(record.transferRate) + '%';
        }
      },
      {
        id: 'weight',
        title: '货物重量',
        field: 'weight',
        minWidth: '150',
        render: ({ record }: { record: ProcessDataItem }) => {
          return `${empty(record.weight)}${empty(record.weightUnit)}`;
        }
      },
      {
        id: 'distance',
        title: '运输距离',
        field: 'distance',
        minWidth: '150',
        render: ({ record }: { record: ProcessDataItem }) => {
          return `${empty(record.distance)}${empty(record.distanceUnit)}`;
        }
      },
      {
        id: 'dosage',
        title: '用量及单位',
        field: 'dosage',
        minWidth: '150',
        render: ({ record }: { record: ProcessDataItem }) => {
          return `${empty(record.dosage)}${empty(record.unit)}`;
        }
      },
      {
        id: 'remark',
        title: '备注',
        field: 'remark',
        minWidth: '150'
      }
    ];
  }
});

function getBind(item: any) {
  const obj = {};
  if (item.width) {
    Object.assign(obj, {
      width: item.width
    });

    return obj;
  }

  if (item.minWidth) {
    Object.assign(obj, {
      minWidth: item.minWidth
    });

    return obj;
  }

  return {
    width: '100'
  };
}

const detailBodyRef = ref();
function handleRefresh(processNo?: string) {
  if (processNo) {
    detailBodyRef.value?.getData(processNo);
  }
  // 刷新总览页数量
  emits('refresh', props.stage);
}

// localValue的格式化
function handleLocalValueFormatter(value: string) {
  return limitStrLength(String(value), 9, true);
}

// 用量更新操作
async function handleDosageUpdate(value: any, row: ProcessDataItem): Promise<boolean> {
  console.log('value', value, row);
  if (!value && value !== 0) {
    createMessage.error('用量不能为空！');
    return Promise.reject(false);
  }
  try {
    const params = {
      ...row,
      dosage: value
    };
    if (row.dataType == 'PART_REPLACE' && props.stage === ProcessStageCodeEnum.USE_STAGE) {
      params.partNodeNo = row.quotationNo;
    }
    if (row.unit == 'pcs') {
      row.quantity = value;
    } else {
      row.dosage = value;
    }
    await editStageFlow(params);
    createMessage.success('编辑用量成功！');
    return Promise.resolve(true);
  } catch (error) {
    return Promise.reject(false);
  }
}
const handleSelect = (row: any) => {
  tableRefs[selectIndex.value]?.operationTable((tableRef: Ref<any>) => {
    const list = tableRef.value?.getData() || [];
    const node = findItemInTree(list, (n: ProcessDataItem) => n.nodeNo === tempNodeNo.value);
    console.log('nodeNo', tempNodeNo.value, list[0].nodeNo);

    // const node = list.find((n: GetListBomTreeResult) => n.nodeNo === row.nodeNo);
    if (node) {
      const productNum = detailBodyRef.value.productNum;
      Object.assign(node, {
        dosage: row.dosage * productNum,
        unit: row.unit
      });
      handleDosageUpdate(row.dosage * productNum, node);
    }
  });
};
</script>

<style lang="scss" scoped>
.dosage-tips-icon {
  color: #96a7b3;
  &:hover {
    color: #03ac82;
  }
}
</style>
